<div id="bonus-list">
    <div class="full">
        <h3 class="h3-title" style="margin: 10px;">{{$t('bgMgr.bonusList')}}</h3>
        <div style="padding-left: 10px;height: 32px;">
            <div style="position: relative;" class="fl">
                <div class="search-wrapper" v-click-outside.capture="onClickOutside">
                    <i-input v-model.trim="sosoValue" icon="ios-close-circle-outline" @on-click="cleanValue" @on-change="sosoValueChange" style="width: 300px;" @on-blur="blur" @on-focus="focus" @on-click="focus"></i-input>
                    <transition name="fade">
                        <div class="search-item-wrapper" v-show="isShowMatchDev">
                            <Tree :data="treeData"></Tree>
                        </div>
                    </transition>
                </div>
            </div>
            <div style="padding-left: 5px;" class="fl">
                <i-button type="primary" @click="handlerClickQuery">{{$t("reportForm.query")}}</i-button>
            </div>
        </div>
        <div class="my-total" style="padding-left: 10px;">
            <span>{{$t("bgMgr.userTotal")}} : {{tableData.length}}</span>
            <span>{{$t("bgMgr.totalGoldenBeans")}} : {{bonuspoints}}</span>
            <span>{{$t("bgMgr.userAmount") }} : {{userbonuspoints}}</span>
            <span>{{$t("bgMgr.totalAmount") }} : {{totalbonuspoints}}</span>
        </div>
        <div style="padding: 0 10px;">
            <i-table border :columns="columns" :data="tableData" :height="taleHeight" size="small" :loading="loading"></i-table>
        </div>
        <Modal v-model="modal" width="300">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="ios-create-outline"></Icon>
                <span>{{$t('monitor.edit')}}</span>
            </p>
            <Row style="margin: 10px 0">
                <i-col span="6" style="height: 100%;text-align:right;line-height:32px;">
                    {{$t("bgMgr.memberUser")}} :
                </i-col>
                <i-col span="16" style="height: 100%;line-height:32px;">
                    {{userName}}
                </i-col>
            </Row>
            <div>
                <Row style="margin: 10px 0">
                    <i-col span="6" style="height: 100%;text-align:right;line-height:32px;">
                        {{$t("bgMgr.transferGoldenBeans")}} :
                    </i-col>
                    <i-col span="16">
                        <input-number :max="10000" :min="0" v-model.trim.number="bonuspoint" style="width: 100%;"></input-number>
                    </i-col>
                </Row>
                <Row style="margin: 10px 0">
                    <i-col span="6" style="height: 100%;text-align:right;line-height:32px;">
                        {{$t("customer.remark")}} :
                    </i-col>
                    <i-col span="16">
                        <i-input v-model.trim="remark" style="width: 100%;"></i-input>
                    </i-col>
                </Row>
            </div>
            <div slot="footer">
                <i-button type="primary" style="width: 100%" @click="handleEdit">{{$t('header.submit')}}</i-button>
            </div>
        </Modal>
    </div>
    <script>
        vueInstanse = new Vue({
            el: "#bonus-list",
            i18n: utils.getI18n(),
            data: {
                loading: true,
                modal: false,
                taleHeight: 300,
                remark: '',
                sosoValue: '',
                columns: [{
                    title: vRoot.$t('user.username'),
                    key: 'username',
                }, {
                    title: vRoot.$t('bgMgr.goldenBeanNumber'),
                    key: 'bonuspoints',
                }, {
                    title: vRoot.$t('alarm.action'),
                    width: 240,
                    render: function(h, params) {
                        var row = params.row;
                        return h(
                            'div', {}, [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            editObject = row;
                                            vueInstanse.type = 'point';
                                            vueInstanse.userName = row.username;
                                            vueInstanse.bonuspoint = String(editObject.bonuspoints);
                                            vueInstanse.modal = true;
                                        }
                                    }
                                }, vRoot.$t('bgMgr.transferGoldenBeans')),
                            ]
                        )
                    },
                }],
                userName: '',
                level: '1',
                createrToUser: userName,
                bonuspoint: 0,
                bonuspoints: 0,
                userbonuspoints: 0,
                tableData: [],
                isShowMatchDev: false,
                treeData: []
            },
            methods: {
                cleanValue: function() {
                    this.sosoValue = '';
                    this.filterMethod(this.sosoValue);
                },
                onClickOutside: function(e) {
                    this.isShowMatchDev = false;
                },
                focus: function() {
                    this.isShowMatchDev = true;
                },
                sosoValueChange: function() {
                    var me = this;
                    var value = this.sosoValue;
                    this.filterMethod(this.sosoValue);
                },
                filterMethod: function(value) {
                    value = value.toLowerCase();
                    this.treeData = [];
                    this.treeData = this.variableDeepSearch(this.groupslist, value, 0);
                    this.checkedDevice = [];
                    if (this.isShowMatchDev == false) {
                        this.isShowMatchDev = true;
                    }
                },
                variableDeepSearch: function(treeDataFilter, searchWord, limitcount) {
                    var childTemp = [];
                    var that = this;
                    for (var i = 0; i < treeDataFilter.length; i++) {
                        var copyItem = null;
                        var item = treeDataFilter[i];
                        if (item != null) {
                            var isFound = false;
                            if (item.title.toLowerCase().indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                                copyItem = deepClone(item);
                                copyItem.expand = false;
                                isFound = true;
                            }
                            if (isFound == false && item.children && item.children.length > 0) {
                                var rs = that.variableDeepSearch(item.children, searchWord, limitcount);
                                if (rs && rs.length > 0) {
                                    copyItem = deepClone(item);
                                    copyItem.children = rs;
                                    copyItem.expand = true;
                                    isFound = true;
                                }
                            }
                            if (isFound == true) {
                                limitcount++;
                                childTemp.push(copyItem);
                                if (limitcount > 100) {
                                    break;
                                }
                            }
                        }
                    }

                    return childTemp;
                },
                castUsersTreeToDevicesTree: function(devicesTreeRecord) {
                    var me = this;
                    var iViewTree = {
                        render: function(h, params) {
                            var username = params.data.title;
                            return h('span', {
                                on: {
                                    'click': function() {
                                        me.createrToUser = username;
                                        me.sosoValue = username;
                                    }
                                },
                                style: {
                                    cursor: 'pointer',
                                    color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                }
                            }, [
                                h('span', [
                                    h('Radio', {
                                        props: {
                                            value: username == me.createrToUser
                                        },
                                        style: {
                                            marginRight: '4px',
                                            marginLeft: '4px'
                                        }
                                    }),
                                    h('span', params.data.title)
                                ]),
                            ])
                        },
                        expand: true,
                    };
                    if (devicesTreeRecord != null) {
                        var username = devicesTreeRecord.user.username;
                        var subusers = devicesTreeRecord.subusers;
                        iViewTree.title = username;
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                            iViewTree.children = subDevicesTreeRecord;

                        }
                    }
                    return iViewTree;
                },
                doCastUsersTreeToDevicesTree: function(usersTrees) {
                    var devicesTreeRecord = [],
                        me = this;
                    if (usersTrees != null && usersTrees.length > 0) {
                        for (var i = 0; i < usersTrees.length; ++i) {
                            var usersTree = usersTrees[i];
                            var username = usersTree.user.username;
                            var subusers = usersTree.subusers;
                            var currentsubDevicesTreeRecord = {
                                render: function(h, params) {
                                    var username = params.data.title;
                                    return h('span', {
                                        on: {
                                            'click': function() {
                                                me.createrToUser = username;
                                                me.sosoValue = username;
                                            }
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                        }
                                    }, [
                                        h('span', [
                                            h('Radio', {
                                                props: {
                                                    value: username == me.createrToUser
                                                },
                                                style: {
                                                    marginRight: '4px',
                                                    marginLeft: '4px'
                                                }
                                            }),
                                            h('span', params.data.title)
                                        ]),
                                    ])
                                },
                            };
                            if (username != null && subusers != null && subusers.length > 0) {
                                // var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                                // currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                            }
                            currentsubDevicesTreeRecord.title = username;
                            devicesTreeRecord.push(currentsubDevicesTreeRecord);
                        }
                    }
                    return devicesTreeRecord;
                },
                queryBonusByUsername: function() {
                    var me = this;
                    var url = myUrls.queryBonusByUsername();
                    utils.sendAjax(url, {}, function(resp) {
                        if (resp.status == 0) {
                            me.bonuspoints = resp.bonuspoints
                        }
                    })
                },
                handlerClickQuery: function() {
                    if (this.sosoValue) {
                        var me = this;
                        var tableData = [];
                        this.records.forEach(function(item) {
                            if (item.username == me.sosoValue || item.username.indexOf(me.sosoValue) != -1) {
                                tableData.push(item);
                            }
                        });
                        me.tableData = tableData;
                    }
                },
                handleEdit: function() {
                    var me = this;

                    if (!(this.bonuspoint > 0)) {
                        me.$Message.error(me.$t('bgMgr.transferGoldenBeansTips3'));
                        return;
                    }
                    var url = myUrls.assignPoints();
                    var data = {
                        targetusername: editObject.username,
                        points: this.bonuspoint,
                        remark: this.remark,
                    };
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status === 0) {
                            me.modal = false;
                            editObject.bonuspoints = resp.topoints;
                            me.bonuspoints = resp.frompoints;
                            me.$Message.success(me.$t('monitor.setupSucc'));
                        } else if (resp.status === 1) {
                            me.$Message.error(vRoot.$t('bgMgr.transferGoldenBeansTips1'));
                        } else if (resp.status === -1) {
                            me.$Message.error(vRoot.$t('bgMgr.transferGoldenBeansTips2'));
                        } else {
                            me.$Message.error(me.$t('monitor.setupFail'));
                        }
                    });


                },
                calcTableHeight: function() {
                    var wHeight = window.innerHeight;
                    this.taleHeight = wHeight - 200;
                },
                queryBonusList: function() {
                    var me = this;
                    var url = myUrls.queryBonusList();
                    var userbonuspoints = 0;
                    utils.sendAjax(url, {}, function(resp) {
                        me.loading = false;
                        if (resp.records) {
                            me.tableData = resp.records;
                            me.records = resp.records;
                            me.records.forEach(function(item) {
                                userbonuspoints += item.bonuspoints;
                            });
                            me.userbonuspoints = userbonuspoints;
                        }
                    }, function() {
                        me.loading = false;
                    })
                },
                queryUsersTree: function(callback) {
                    var url = myUrls.queryUsersTree(),
                        me = this;
                    utils.sendAjax(url, {
                        username: userName
                    }, function(respData) {
                        if (respData.status == 0 && respData.rootuser.user) {
                            callback([me.castUsersTreeToDevicesTree(respData.rootuser)]);
                        } else {
                            me.$Message.error(me.$t('monitor.queryFail'))
                        }
                    });
                },
            },
            computed: {
                totalbonuspoints: function() {
                    return this.userbonuspoints + this.bonuspoints;
                }
            },
            // watch: {
            //     queryParameter: function(newVal) {
            //         if (newVal == "") {
            //             this.tableData = this.records;
            //         }
            //     }
            // },
            mounted: function() {
                var me = this;
                me.records = [];
                this.calcTableHeight();
                this.queryBonusList();
                this.queryBonusByUsername();
                var me = this;
                me.queryUsersTree(function(usersTree) {
                    me.groupslist = usersTree;
                    me.treeData = usersTree;
                });
                window.onresize = function() {
                    me.calcTableHeight();
                }
            }
        })
    </script>
</div>